import {
    reqShopCartList,
    changeShopCartChecked,
    deleteShopCart
} from '@/api';

const actions = {
    //获取购物车列表
    async getShopCartList({
        commit
    }) {
        let result = await reqShopCartList();
        if (result.code == 200) {
            //数据在数组的第一个元素上,如果数组为空,则返回一个空对象
            commit('GET_SHOP_CART_LIST', result.data[0] || {});
        }
    },

    //修改商品选中状态
    async changeChecked({
        commit
    }, {
        skuId,
        isChecked
    }) {
        let result = await changeShopCartChecked(skuId, isChecked);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },

    //修改全部商品的选中状态
    changeAllChecked({
        state,
        commit,
        dispatch
    }, checked) {
        let arr = [];
        state.shopCartList.cartInfoList.forEach(item => {
            if (item.isChecked !== checked) {
                let promise = dispatch('changeChecked', {
                    skuId: item.skuId,
                    isChecked: checked
                });
                arr.push(promise);
            }
        });
        return Promise.all(arr);
    },

    //删除商品
    async deleteShopCart({
        commit
    }, skuId) {
        let result = await deleteShopCart(skuId);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(result.message);
        }
    },

    //删除已选中的商品
    deleteAllChecked({
        state,
        dispatch
    }) {
        let arr = [];
        state.shopCartList.cartInfoList.forEach(async item => {
            if (item.isChecked) {
                let promise = await dispatch('deleteShopCart', item.skuId);
                arr.push(promise);
            }

        });
        return Promise.all(arr);
    }
}

const mutations = {
    GET_SHOP_CART_LIST(state, value) {
        state.shopCartList = value;
    }
}

const getters = {
    cartInfoList() {
        return state.shopCartList.cartInfoList || [];
    }
}

const state = {
    shopCartList: {}
}

export default {
    actions,
    mutations,
    getters,
    state
}